from pandas import read_csv
from datetime import datetime
from typing import Literal
from .config import config

LocationType = Literal['longlat', 'id']

def get_location(location: str, type: LocationType='longlat') -> str:
    """### Get location from city database"""
    # Read city.csv
    data = read_csv(config.city_csv)
    # Get location_en and location_zh
    location_en = data['Location_Name_EN']
    location_zh = data['Location_Name_ZH']
    # Get mask
    mask = (location_en.str.lower() == location.lower()) | \
        (location_zh.str.lower() == location.lower())
    # Get matching rows
    matching_rows = data[mask]
    # Get first matching row
    if not matching_rows.empty:
        if type == 'longlat':
            first_match = matching_rows.iloc[0]
            # Get longitude and latitude
            longitude = first_match['Longitude']
            latitude = first_match['Latitude']
            return f'{longitude:.2f},{latitude:.2f}'
        elif type == 'id':
            first_match = matching_rows.iloc[0]
            return first_match['Location_ID']
    else:
        raise ValueError(f'Location {location} not found')

def format_time(time: str, fmt: str='%Y-%m-%d %H:%M:%S') -> str:
    """### Change time format"""
    dt = datetime.fromisoformat(time)
    return dt.strftime(fmt)
